# coding=utf-8
# 获取指数涨跌
import collections
import os
import re

import akshare as ak
import pandas
import pandas as pd
from loguru import logger

from models.stock_model import StockNumber, DayInfo
from mylib.download_all import analysis_stock
from mylib.mycsv import sort_csv


def run(d=1):
    if d:
        sz_index_df = ak.index_zh_a_hist(symbol="000001", period="daily")
        df_sorted = sz_index_df.sort_values(by='日期', ascending=False)
        df_sorted.to_csv("shanghai_index.csv", index=False)
    else:
        df_sorted = pd.read_csv('shanghai_index.csv')
    today_date = eval(str(list(df_sorted['日期'])[0]).replace('-', ''))
    return today_date


def get_upup(today_date, sn):
    res_dict = collections.defaultdict(list)
    sc = f'stocks/{sn.ts_code}.csv'
    if not os.path.exists(sc):
        return None
    df = pandas.read_csv(sc)
    if str(df['trade_date'][0]) != str(today_date):
        analysis_stock(sn)
        df = pandas.read_csv(sc)

    temp_arr = []
    for row in df.index:
        if row > 100:
            break
        if row == 0:
            continue
        d_pre = DayInfo(sn, df.loc[row - 1])
        d = DayInfo(sn, df.loc[row])
        if d_pre.pct_chg > 1 and d.pct_chg > 1 and d_pre.vol > d.vol:
            if not temp_arr:
                temp_arr.append(d_pre)
            temp_arr.append(d)
            continue
        if len(temp_arr) > 2:
            res_dict[(d_pre.trade_date, row)].extend(temp_arr)
        temp_arr = []
    res = re.findall('stocks/(.*).csv', sc)
    link_code_arr = res[0].split('.')
    link_code = f'{link_code_arr[1]}{link_code_arr[0]}'
    hyperlink = f'"https://xueqiu.com/S/{link_code}"'
    date_arr_hyp = f'{res[0]},=HYPERLINK({hyperlink})'
    return date_arr_hyp, res_dict


def get_all_stock_csv_path():
    for root, dirs, files in os.walk('stocks'):
        return [os.path.join(root, item) for item in files]


if __name__ == '__main__':
    D = True
    today_date = run(D)
    df = pd.read_csv('all.csv')
    full_path_txt = f'{today_date}_get_upup.txt'
    full_path_csv = f'{today_date}_get_upup.csv'
    if os.path.exists(full_path_txt):
        os.remove(full_path_txt)
    logger.add(full_path_txt, format='{message}')
    n_arr = []
    ts_code_arr = []
    result_dict = {}
    cnt = 0
    with open(full_path_csv, 'w', encoding='utf-8') as aa:
        aa.write(f'AA,BB,CC,DD,EE,FF')
        for row in df.index:
            # if cnt > 10:
            #     break
            sn = StockNumber(df.loc[row])
            try:
                date_arr_hyp, res_dict = get_upup(today_date, sn)
                pre_k = None
                pre_v = None
                msg_arr = []
                all_date = set()
                for k, v in res_dict.items():
                    if pre_k and k[1] - pre_k[1] < 20:
                        msg_arr.append(date_arr_hyp)
                        for x in pre_v:
                            msg_arr.append(x)
                            all_date.add(x.trade_date)
                        msg_arr.append('-' * 10)
                        for x in v:
                            msg_arr.append(x)
                            all_date.add(x.trade_date)
                        msg_arr.append('=' * 10)
                    pre_k = k
                    pre_v = v
                if not msg_arr:
                    continue
                cnt += 1
                for m in msg_arr[::-1]:
                    logger.info(m)
                all_date_sort = sorted(all_date, reverse=True)
                w_msg = f'\n{all_date_sort[0]},{len(all_date)},{sn.industry},{sn.name},{date_arr_hyp}'
                aa.write(w_msg)
            except Exception as e:
                print(e)
    sort_csv(full_path_csv, ['AA', 'BB'], [False, False])
